package handler

import (
	"context"
	"gitee.com/fanbuchi/mocker/srv/repository"

	"github.com/micro/go-micro/util/log"

	mocker "gitee.com/fanbuchi/mocker/srv/proto/mocker"
)

type Mocker struct{
	Repo *repository.Mocker
}

// Call is a single request handler called via client.Call or the generated client code
func (e *Mocker) Call(ctx context.Context, req *mocker.Request, rsp *mocker.Response) error {
	log.Log("Received Mocker.Call request")
	rsp.Msg = "Hello " + req.Name

	return nil
}

func (e *Mocker) CreateMocker(ctx context.Context, req *mocker.Mockers, rsp *mocker.Mockers) error {
	log.Log("Received Mocker.Call request")
	if err := e.Repo.CreateMocker(req); err != nil {
		return nil
	}
	rsp=req
	return nil
}


func (e *Mocker) DeleteMocker(ctx context.Context, req *mocker.Mockers, rsp *mocker.Rsp) error {

	if req.Id==0 {
		result,err:=e.Repo.FindOne(req.Id)
		if err!=nil {
			return err
		}
		req.Id=result.Id
	}
	if err := e.Repo.DeleteMocker(req.Id); err != nil {
		return nil
	}
	return nil
}

func (e *Mocker) UpdateMocker(ctx context.Context, req *mocker.Mockers, rsp *mocker.Rsp) error {
	out,err := e.Repo.UpdateMocker(req)
	if  err != nil {
		return nil
	}
	rsp.Data=out
	return nil
}


func (e *Mocker) QueryMocker(ctx context.Context, req *mocker.Mockers, rsp *mocker.Rsp) error {
	result,err:=e.Repo.FindOne(req.Id)
	if err!=nil {
		return err
	}
	rsp.Data=result
	return nil
}


func (e *Mocker) SearchMocker(ctx context.Context, req *mocker.Page, rsp *mocker.RspList) error {
	log.Log("Received Mocker.Call request")
	if req.Param==nil {
		req.Param = &mocker.Mockers{}
	}
	result,err:=e.Repo.SearchByField(req)
	if err!=nil {
		return err
	}
	rsp.DataList=*result
	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *Mocker) Stream(ctx context.Context, req *mocker.StreamingRequest, stream mocker.Mocker_StreamStream) error {
	log.Logf("Received Mocker.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&mocker.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *Mocker) PingPong(ctx context.Context, stream mocker.Mocker_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&mocker.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
